package com.linkoog.devtools.http.request.http_request.request_body.body;

import com.intellij.ui.components.JBScrollPane;
import com.linkoog.devtools.http.request.common.request_body.UrlEncodeFormRequestBody;
import com.linkoog.devtools.http.request.http_request.request_body.BodyPanel;
import com.linkoog.devtools.intellij.ui.table.ListTableView;
import com.linkoog.devtools.intellij.ui.table.row_data.KeyValWithCheckedTableRowData;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Getter
public class UrlEncodedFormPanel extends JPanel implements BodyPanel<UrlEncodeFormRequestBody> {

    private final ListTableView<KeyValWithCheckedTableRowData> paramTable;

    public UrlEncodedFormPanel() {
        super(new BorderLayout());

        paramTable = KeyValWithCheckedTableRowData.createListTableView();
        JBScrollPane scrollPane = new JBScrollPane();
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setViewportView(paramTable);
        add(scrollPane, BorderLayout.CENTER);
    }

    @Override
    public void resetRequestBody(@NotNull UrlEncodeFormRequestBody requestBody) {
        Map<String, List<String>> dataMap = requestBody.getDataMap();
        if (dataMap == null || dataMap.isEmpty()){
            return;
        }

        List<KeyValWithCheckedTableRowData> list = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : dataMap.entrySet()) {
            List<String> values = entry.getValue();
            if (values == null || values.isEmpty()){
                continue;
            }

            for (String value : values) {
                KeyValWithCheckedTableRowData rowData = new KeyValWithCheckedTableRowData();
                rowData.setChecked(true);
                rowData.setKey(entry.getKey());
                rowData.setValue(value);
                list.add(rowData);
            }
        }
        paramTable.reloadData(list);
    }

    @Override
    public @NotNull UrlEncodeFormRequestBody buildRequestBody() {
        if (paramTable.getRowCount() > 0){
            Map<String, List<String>> dataMap = KeyValWithCheckedTableRowData.getKeyValue(paramTable);
            return UrlEncodeFormRequestBody.of(dataMap);
        }
        return UrlEncodeFormRequestBody.of(new LinkedHashMap<>());
    }

    @Override
    public JPanel getPanel() {
        return this;
    }


}
